package us.mooresr.geartrack.server.handler;

import java.util.Date;
import java.util.List;

import us.mooresr.geartrack.server.DAO;
import us.mooresr.geartrack.shared.action.CheckInItemAction;
import us.mooresr.geartrack.shared.action.CheckInItemResult;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.Loan;

import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class CheckInItemActionHandler 
	implements ActionHandler<CheckInItemAction, CheckInItemResult> {

	@Override
	public CheckInItemResult execute(CheckInItemAction action,
			ExecutionContext arg1) throws ActionException {
		DAO dao = new DAO();
		
		Long itemId = action.getItemId();
		
		List<Loan> loanList = dao.ofy().query(Loan.class).filter("checkInDate", null).list();
		
		for (Loan l : loanList) {
			if (l.getItemId().equals(itemId)) {
				l.setCheckInDate(new Date());
				dao.ofy().put(l);
			}
		}
		
		Item returnedItem = dao.ofy().get(Item.class, itemId);
		
		return new CheckInItemResult(returnedItem);

	}

	@Override
	public Class<CheckInItemAction> getActionType() {
		return CheckInItemAction.class;
	}

	@Override
	public void undo(CheckInItemAction arg0, CheckInItemResult arg1,
			ExecutionContext arg2) throws ActionException {
		// TODO Auto-generated method stub
		
	}


}
